package ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.linchaolong.android.imagepicker.ImagePicker;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.DoTheWorkSelectAdapter;
import adapter.GridImageAdapter;
import application.App;
import base.BaseBean;
import base.activity.BaseNetActivity;
import bean.ListOfPapersBean;
import jp.wasabeef.richeditor.RichEditor;
import student.andlei.com.student.R;
import utils.GsonUtils;
import utils.QiniuUploadUtils;
import utils.SPUtils;
import utils.StringUtils;
import utils.TimeUtil;
import utils.TimerUtil;
import view.ConfirmPopWindow;

public class DoTheWorkActivity extends BaseNetActivity {
    /*****************计时器*******************/
    private Runnable timeRunable = new Runnable() {
        @Override
        public void run() {
            currentSecond = currentSecond + 1000;
            tv_time.setText(TimeUtil.getFormatHMS(currentSecond));
            if (!isPause) {
                //递归调用本runable对象，实现每隔一秒一次执行任务
                mhandle.postDelayed(this, 1000);
            }
        }
    };
    //计时器
    private Handler mhandle = new Handler();
    private boolean isPause = false;//是否暂停
    private long currentSecond = 0;//当前毫秒数
    /*****************计时器*******************/
    private int maxSelectNum = 3;
    private TextView tv_numbr,
            tv_time,
            tv_answersheet,
            tv_scrappaper;
    private TextView tv_typename;
    private RichEditor tv_content;

    private CheckBox check_shoucang;
    private ImageView check_pen,
            check_rubber;
    private List<ListOfPapersBean.mList.Questions.Options> optionsList = new ArrayList<>();
    private DoTheWorkSelectAdapter selectAdapter;
    private RecyclerView recy_xuanze;
    //    private LinearLayout layout_pen,
//            layout_rubber,
//            layout_wacom;
    private LinearLayout layout_wacom;
    private RichEditor ed_content;
    private ImageView img_photo, img_camera, img_update;
    //private List<String> list;
    private ImagePicker imagePicker;
    // private RecyclerView gv;
    //  private GridImageAdapter adapter;
    private ImageView img_left,
            img_right,
            img_clean;
    private ScrollView scrollView;
    //    private LinePathView paletteView;
    //private ImageView img_wacom;
    private List<ListOfPapersBean.mList.Questions> mLists = new ArrayList<>();
    private View layoutview;
    private int paper_id;//试卷id
    private int paper_question_id;//题目id
    private int question_id;
    private int student_task_id; // 学生作业id
    private int  task_id = 0;
    private int answer_id;//答题卡id
    private int check_type;//1:收藏（默认） 2:取消收藏
    private String drawing_board_image = "";//手写板图片
    private String answer_image;//上传图片

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseBack(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    @Override
    public void success(String action, BaseBean baseBean) {
        hideLoadDialog();
        if (baseBean.code == 200) {
            if (action.equals("Task/getAllQuestion")) {
                ListOfPapersBean bean = (ListOfPapersBean) GsonUtils.getInstance(this).parseComplexJArrayByCommon(baseBean, ListOfPapersBean.class);
                student_task_id = bean.student_task_id;
                answer_id = bean.answer_id;
                if (!StringUtils.isNull(SPUtils.getInstance(App.getInstance()).getString(answer_id + "worktime"))) {
                    currentSecond = TimerUtil.GetS(SPUtils.getInstance(App.getInstance()).getString(answer_id + "worktime"));
                }
                timeRunable.run();
                if (bean.list == null) {
                    toast("暂无数据");
                    finish();
                    return;
                }
                mLists.clear();
                for (int i = 0; i < bean.list.size(); i++) {
                    //bean.list.get(i).type_name
                    for (int j = 0; j < bean.list.get(i).questions.size(); j++) {
                        bean.list.get(i).questions.get(j).type_id = bean.list.get(i).type_id;
                        bean.list.get(i).questions.get(j).type_name = bean.list.get(i).type_name;
                    }

                    mLists.addAll(bean.list.get(i).questions);
                }
                if (mLists.size() <= 0) {
                    toast("暂无数据");
                    finish();
                }
                for (int h = 0; h < mLists.size(); h++) {
                    if( mLists.get(h).options ==null){   toast("暂无数据");finish(); return;}
                    for (int n = 0; n < mLists.get(h).options.size(); n++) {
                        if (!StringUtils.isNull(mLists.get(h).answer)) {
                            if (mLists.get(h).answer.equals(mLists.get(h).options.get(n).idx)) {
                                mLists.get(h).options.get(n).isSelect = 1;
                            } else {
                                mLists.get(h).options.get(n).isSelect = 0;
                            }
                        }
                    }
//                    if (!StringUtils.isNull(mLists.get(h).answer_image)) {
//                        String[] img_arry = mLists.get(h).answer_image.split("|");
//                        for (int i = 0; i < img_arry.length; i++) {
//                            if (!StringUtils.isNull(img_arry[i])) {
//                                LocalMedia localMedia = new LocalMedia();
//                                localMedia.setCompressPath(img_arry[i]);
//                                localMedia.setPath(img_arry[i]);
//                                mLists.get(h).imglist = new ArrayList<>();
//                                mLists.get(h).imglist.add(localMedia);
//                            }
//                        }
//                    }
                    if (!StringUtils.isNull(mLists.get(h).drawing_board_image)) {
                        mLists.get(h).shouxieimg = mLists.get(h).drawing_board_image;
                        // loadImageSimpleTarget(mLists.get(h).shouxieimg);
                    }
                }
                updateUi(i);
            } else if (action.equals("Task/getQuestion")) {


            } else if (action.equals("Task/collectQuestion")) {
                if (check_type == 1) {
                    mLists.get(i).is_favorite = 1;
                    check_shoucang.setChecked(true);
                    check_shoucang.setText("  已收藏");
                } else {
                    mLists.get(i).is_favorite = 0;
                    check_shoucang.setChecked(false);
                    check_shoucang.setText("  未收藏");
                }
            } else if (action.equals("Task/saveAnswer")) {

                selectList.clear();
                //adapter.notifyDataSetChanged();
                PictureFileUtils.deleteCacheDirFile(DoTheWorkActivity.this);
            }
        } else {
            if (action.equals("Task/collectQuestion")) {
                if (check_shoucang.isChecked()) {
                    check_shoucang.setChecked(false);
                } else {
                    check_shoucang.setChecked(true);
                }
//                if(check_type==1){
//                    mLists.get(i).is_favorite = 1;
//                    check_shoucang.setChecked(true);
//                    check_shoucang.setText("  已收藏");
//                }else {
//                    mLists.get(i).is_favorite = 0;
//                    check_shoucang.setChecked(false);
//                    check_shoucang.setText("  未收藏");
//                }
            }
            toast(baseBean.getMsg());
        }
    }

    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
    }

    @Override
    protected int getLayoutId() {
        layoutview = View.inflate(context, R.layout.activity_dothework, null);
        return R.layout.activity_dothework;
    }

    @SuppressLint("Range")
    @Override
    protected void findViews() {
        tv_numbr = getView(R.id.tv_number);
        tv_time = getView(R.id.tv_time);
        //输入答案
        ed_content = getView(R.id.ed_content);
        //选择图片 手写板
        check_shoucang = getView(R.id.check_shoucang_);
        tv_answersheet = getView(R.id.tv_answersheet);
        tv_scrappaper = getView(R.id.tv_Scrappaper);
        tv_typename = getView(R.id.tv_answertype);
        tv_content = getView(R.id.tv_content);
        tv_content.setInputEnabled(false);
        tv_content.setInitialScale(300);
        check_pen = getView(R.id.check_pen);
        check_rubber = getView(R.id.check_rubber);
        recy_xuanze = getView(R.id.rycl_xuanze);
        // img_wacom = getView(R.id.img_wacom);
        layout_wacom = getView(R.id.layout_wacom);
//        layout_pen = getView(R.id.layout_pen);
//        layout_rubber = getView(R.id.layout_rubber);
        img_clean = getView(R.id.img_clean);
        scrollView = getView(R.id.scrollView);
//        paletteView = getView(R.id.plt_wacom);
        img_left = getView(R.id.img_left);
        img_right = getView(R.id.img_right);
        //gv = getView(R.id.grid_view);
    }

//    private void initImagePicker() {
//        GridLayoutManager manager = new GridLayoutManager(context, 6, GridLayoutManager.VERTICAL, false);
//        //gv.setLayoutManager(manager);
//        adapter = new GridImageAdapter(context, onAddPicClickListener,false);
//        adapter.setList(selectList);
//        adapter.setSelectMax(maxSelectNum);
//       // gv.setAdapter(adapter);
//        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(int position, View v) {
//                if (selectList.size() <= 0) {
//                    return;
//                }
//                LocalMedia media = selectList.get(position);
//                String pictureType = media.getPictureType();
//                int mediaType = PictureMimeType.pictureToVideo(pictureType);
//                switch (mediaType) {
//                    case 1:
//                        // 预览图片
//                        PictureSelector.create(DoTheWorkActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
//                        break;
//                }
//            }
//        });
//    }

    @Override
    protected void formatViews() {
        tv_answersheet.setOnClickListener(this);
        tv_scrappaper.setOnClickListener(this);
        initRichEditor();
        img_photo = getView(R.id.iv_picture_overkeyloard_addnote);
        img_camera = getView(R.id.iv_camera_overkeyloard_addnote);
        img_update = getView(R.id.iv_drawingboard_overkeyloard_addnote);
        img_photo.setOnClickListener(this);
        img_camera.setOnClickListener(this);
        img_update.setOnClickListener(this);
//        img_clean.setOnClickListener(this);
        img_left.setOnClickListener(this);
        img_right.setOnClickListener(this);
//        check_pen.setOnClickListener(this);
//        check_rubber.setOnClickListener(this);
        check_shoucang.setOnClickListener(this);

//        layout_pen.setBackgroundResource(R.color.check_color);
//        initImagePicker();
        ed_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    //mLists.get(i).shouxieimg = paletteView.getBitMap();
//                    if (mLists.size() > 0) {
//                        String mpath = "/sdcard/dskqxt/pic/" + mLists.get(i).paper_question_id + ".jpg";
//                        //String mpath = App.getAppCacheDir(DoTheWorkActivity.this) + mLists.get(i).paper_question_id + ".jpg";
//                        //"/sdcard/dskqxt/pic/"
//                        try {
//                            paletteView.save(mpath, paletteView.getBitMap());
//                            mLists.get(i).shouxieimg = mpath;
//                            LogUtil.app("----->手写板对象已赋值");
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    scrollView.requestDisallowInterceptTouchEvent(false);
                } else {
                    //不允许ScrollView截断点击事件，点击事件由子View处理
                    scrollView.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
    }

    @Override
    protected void formatData() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recy_xuanze.setLayoutManager(layoutManager);
        selectAdapter = new DoTheWorkSelectAdapter(R.layout.item_work_select, optionsList);
        recy_xuanze.setAdapter(selectAdapter);
        selectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mLists.get(i).type_id == 2) {
                    if(optionsList.get(position).getIsSelect() == 1){
                        optionsList.get(position).setIsSelect(0);
                    }else {
                        optionsList.get(position).setIsSelect(1);
                    }
                } else {
                    for (int i = 0; i < optionsList.size(); i++) {
                        if (position == i) {
                            optionsList.get(position).setIsSelect(1);
                            //optionsList.get(i).isSelect = 1;
                        } else {
                            optionsList.get(i).setIsSelect(0);
                            //optionsList.get(i).isSelect = 0;
                        }
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
        tv_numbr.setText((i + 1) + "/" + mLists.size() + "题");
        loadDataList();
    }

    private void loadDataList() {
        Map<String, String> map = new HashMap<>();
        if(student_task_id>0){
            map.put("student_task_id", "" + student_task_id);
        }else {
            map.put("task_id",task_id+"");
        }
        post("Task/getAllQuestion", map, BaseBean.class, false);

    }

    private void checkTogglet() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "" + check_type);
        map.put("question_id", "" + mLists.get(i).question_id);
        post("Task/collectQuestion", map, BaseBean.class, true);
    }

    private void loadData(String paper_question_id, String answer_id) {
        Map<String, String> map = new HashMap<>();
        map.put("paper_question_id", "" + paper_question_id);
        map.put("answer_id", "" + answer_id);
        post("Task/getQuestion", map, BaseBean.class, false);
    }

    @Override
    protected void getBundle(Bundle bundle) {
        paper_id = bundle.getInt("paper_id");
        student_task_id = bundle.getInt("student_task_id");
        task_id = bundle.getInt("task_id");
        setTitle("" + bundle.getString("title"));
    }

    private void initRichEditor() {
//        retNoteContent.setEditorHeight(DensityUtil.dip2px(EditNoteActivity.this,287));
        ed_content.setEditorFontSize(20);
        ed_content.setPlaceholder("请输入答案");
        ed_content.setEditorFontColor(getResources().getColor(R.color.font_black));
        ed_content.setPadding(33, 26, 33, 26);
        ed_content.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
            @Override
            public void onTextChange(String text) {
//                content=text;
//                Logger.i("Logger","content"+text);
            }
        });
    }

    private int i = 0;

    @SuppressLint("Range")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //向左按钮
            case R.id.img_left:
                if (i <= 0) {
                    //toast("已是第一题");
                    return;
                }
                leftorRight();
                i--;
//                paletteView.clear();
                updateUi(i);
                break;
            //向右按钮
            case R.id.img_right:
                if (i >= mLists.size() - 1) {
                    leftorRight();
                    Bundle bundle = new Bundle();
                    bundle.putInt("student_task_id", student_task_id);
                    bundle.putInt("answer_id", answer_id);
                    jumpTo(AnswerSheetActivity.class, 0, bundle);
                    //toast("已是最后一题");
                    return;
                }
                leftorRight();
                i++;
//                paletteView.clear();
                updateUi(i);
                break;
            //画笔
            case R.id.check_pen:
                //toast("画笔");
//                paletteView.setPenColor(Color.BLACK);
//                paletteView.setPaintWidth(5);
                // paletteView.setMode(PaletteView.Mode.DRAW);
//                layout_pen.setBackgroundResource(R.color.check_color);
//                layout_rubber.setBackgroundResource(R.color.uncheck_color);
                break;
            //橡皮
            case R.id.check_rubber:
                //toast("橡皮");
//                paletteView.setPenColor(Color.WHITE);
//                paletteView.setPaintWidth(50);
                // paletteView.setMode(PaletteView.Mode.ERASER);
//                layout_rubber.setBackgroundResource(R.color.check_color);
//                layout_pen.setBackgroundResource(R.color.uncheck_color);
                break;
            //清除手写板按钮
            case R.id.img_clean:
                //toast("清除手写板按钮");
//                paletteView.clear();
//                String mpath = "/sdcard/dskqxt/pic/" + mLists.get(i).paper_question_id + ".jpg";
//                try {
//                    paletteView.save(mpath, paletteView.getBitMap());
//                    mLists.get(i).shouxieimg = "";
//                    LogUtil.app("----->手写板对象已赋值");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                break;
            //草稿本
            case R.id.tv_Scrappaper:
                new ConfirmPopWindow(this).showAtBottom(layoutview);
                break;
            //答题卡
            case R.id.tv_answersheet:
                leftorRight();
                Bundle bundle = new Bundle();
                bundle.putInt("student_task_id", student_task_id);
                bundle.putInt("answer_id", answer_id);
                jumpTo(AnswerSheetActivity.class, 0, bundle);
                break;
            //收藏按钮
            case R.id.check_shoucang_:
                //1:收藏（默认） 2:取消收藏
                if (check_shoucang.isChecked()) {
                    check_type = 1;
                } else {
                    check_type = 2;
                }
                checkTogglet();
                break;
            //选择图片
            case R.id.iv_picture_overkeyloard_addnote:

                openPhoto();
                ed_content.setFocusable(true);
                ed_content.setFocusableInTouchMode(true);
                ed_content.requestFocus();
                break;
            //拍照
            case R.id.iv_camera_overkeyloard_addnote:

                openCamera();
                ed_content.setFocusable(true);
                ed_content.setFocusableInTouchMode(true);
                ed_content.requestFocus();
                break;
            //添加手写板图
            case R.id.iv_drawingboard_overkeyloard_addnote:

                jumpTo(AddWacomActivity.class, 0);
                ed_content.setFocusable(true);
                ed_content.setFocusableInTouchMode(true);
                ed_content.requestFocus();
                break;
        }
    }

    private void leftorRight() {
        if (mLists.size() > 0) {
            paper_question_id = mLists.get(i).paper_question_id;
            drawing_board_image = mLists.get(i).shouxieimg;
            mLists.get(i).answer_image = ed_content.getHtml();
            savedata();
        }
    }

    private void updateUi(int i) {
        tv_numbr.setText((i + 1) + "/" + mLists.size() + "题");
        tv_typename.setText("(" + mLists.get(i).type_name + ")");
        // RichText.fromHtml(mLists.get(i).question_content).into(tv_content);
        tv_content.setHtml(mLists.get(i).question_content);

        // tv_content.setText(mLists.get(i).question_content);
        optionsList = mLists.get(i).options;
        selectAdapter.setNewData(optionsList);
        if (mLists.get(i).is_favorite == 0) {
            check_shoucang.setChecked(false);
            check_shoucang.setText("  未收藏");
        } else {
            check_shoucang.setChecked(true);
            check_shoucang.setText("  已收藏");
        }
        Log.i("imglist--->", "" + mLists.get(i).answer_image);
        ed_content.setHtml(mLists.get(i).answer_image);
//        if (mLists.get(i).imglist != null && mLists.get(i).imglist.size() > 0) {
////            adapter.setList(mLists.get(i).imglist);
////            adapter.notifyDataSetChanged();
//        } else {
//            List<LocalMedia> mediaList = new ArrayList<>();
////            adapter.setList(mediaList);
////            adapter.notifyDataSetChanged();
//        }
//        if (!StringUtils.isNull(mLists.get(i).shouxieimg)) {
//            if (mLists.get(i).shouxieimg.contains("http")) {
//
//
//                    Log.i("shouxieimg", i + "-----" + mLists.get(i).shouxieimg);
////                    loadImageSimpleTarget(mLists.get(i).shouxieimg);
//
//            } else {
//                Bitmap bmp = BitmapFactory.decodeFile(mLists.get(i).shouxieimg);//filePath
//                Drawable drawable = new BitmapDrawable(bmp);
////                paletteView.setBackground(drawable);
//            }
//        }
        //1.单选题，2.多选题，3.判断题，4.填空题，5.解答题，6.实验题，7.作文题
        switch (mLists.get(i).type_id) {
            case 1:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 2:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 3:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 4:
//                ed_content.setFocusable(true);
//                ed_content.setFocusableInTouchMode(true);
//                ed_content.requestFocus();

                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
            case 5:

                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
            case 6:
//                ed_content.setFocusable(true);
//                ed_content.setFocusableInTouchMode(true);
//                ed_content.requestFocus();
                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
            case 7:
//                ed_content.setFocusable(true);
//                ed_content.setFocusableInTouchMode(true);
//                ed_content.requestFocus();
                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
            default:
//                ed_content.setFocusable(true);
//                ed_content.setFocusableInTouchMode(true);
//                ed_content.requestFocus();
                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
        }
    }

//    private void SaveData() {
//        showLoadDialog();
//        final String yuming = SPUtils.getInstance(DoTheWorkActivity.this).getString("domain");
//        if (!StringUtils.isNull(drawing_board_image) && selectList.size() > 0) {
//            if (drawing_board_image.contains("http") && selectList.get(0).getPath().contains("http")) {
//                String image = "";
//                for (LocalMedia s : selectList) {
//                    image = image + "|" + s.getPath();
//                    Log.i("image", "" + image);
//                }
//                savedata(drawing_board_image, image);
//            } else if (drawing_board_image.contains("http") && !selectList.get(0).getPath().contains("http")) {
//                List<String> list = new ArrayList<>();
//                for (int i = 0; i < selectList.size(); i++) {
//                    list.add(selectList.get(i).getCompressPath());
//                }
//                QiniuUploadUtils.getInstance().uploadMutliFiles(list, new QiniuUploadUtils.UploadMutliListener() {
//                    @Override
//                    public void onUploadMutliSuccess(List<String> list) {
//                        String image = "";
//                        for (String s : list) {
//                            image = image + "|" + (yuming + s);
//                            Log.i("image", "" + image);
//                        }
//                        savedata(drawing_board_image, image);
//                    }
//
//                    @Override
//                    public void onUploadMutliFail(Error error) {
//
//                    }
//                }, SPUtils.getInstance(context).getString("uptoken"));
//            } else if (!drawing_board_image.contains("http") && selectList.get(0).getPath().contains("http")) {
//                QiniuUploadUtils.getInstance().uploadFile(drawing_board_image, new QiniuUploadUtils.UploadListener() {
//                    @Override
//                    public void onUploadSuccess(String key) {
//                        drawing_board_image = yuming + key;
//                        String image = "";
//                        for (LocalMedia s : selectList) {
//                            image = image + "|" + s.getPath();
//                            Log.i("image", "" + image);
//                        }
//                        savedata(drawing_board_image, image);
//                    }
//
//                    @Override
//                    public void onUploadFail(Error error) {
//
//                    }
//                }, SPUtils.getInstance(context).getString("uptoken"));
//            } else {
//                QiniuUploadUtils.getInstance().uploadFile(drawing_board_image, new QiniuUploadUtils.UploadListener() {
//                    @Override
//                    public void onUploadSuccess(String key) {
//                        drawing_board_image = yuming + key;
//                        List<String> list = new ArrayList<>();
//                        for (int i = 0; i < selectList.size(); i++) {
//                            list.add(selectList.get(i).getCompressPath());
//                        }
//                        QiniuUploadUtils.getInstance().uploadMutliFiles(list, new QiniuUploadUtils.UploadMutliListener() {
//                            @Override
//                            public void onUploadMutliSuccess(List<String> list) {
//                                String image = "";
//                                for (String s : list) {
//                                    image = image + "|" + (yuming + s);
//                                    Log.i("image", "" + image);
//                                }
//                                savedata(drawing_board_image, image);
//                            }
//
//                            @Override
//                            public void onUploadMutliFail(Error error) {
//
//                            }
//                        }, SPUtils.getInstance(context).getString("uptoken"));
//                    }
//
//                    @Override
//                    public void onUploadFail(Error error) {
//
//                    }
//                }, SPUtils.getInstance(context).getString("uptoken"));
//            }
//
//        } else if (!StringUtils.isNull(drawing_board_image) && selectList.size() == 0) {
//            if (drawing_board_image.contains("http")) {
//                savedata(drawing_board_image, "");
//            } else {
//                QiniuUploadUtils.getInstance().uploadFile(drawing_board_image, new QiniuUploadUtils.UploadListener() {
//                    @Override
//                    public void onUploadSuccess(String key) {
//                        drawing_board_image = yuming + key;
//                        savedata(drawing_board_image, "");
//                    }
//
//                    @Override
//                    public void onUploadFail(Error error) {
//                    }
//                }, SPUtils.getInstance(context).getString("uptoken"));
//            }
//
//        } else if (StringUtils.isNull(drawing_board_image) && selectList.size() > 0) {
//            if (selectList.get(0).getPath().contains("http")) {
//                String image = "";
//                for (LocalMedia s : selectList) {
//                    image = image + "|" + s.getPath();
//                    Log.i("image", "" + image);
//                }
//                savedata("", image);
//            } else {
//                List<String> list = new ArrayList<>();
//                for (int i = 0; i < selectList.size(); i++) {
//                    list.add(selectList.get(i).getCompressPath());
//                }
//                QiniuUploadUtils.getInstance().uploadMutliFiles(list, new QiniuUploadUtils.UploadMutliListener() {
//                    @Override
//                    public void onUploadMutliSuccess(List<String> list) {
//                        String image = "";
//                        for (String s : list) {
//                            image = image + "|" + (yuming + s);
//                            Log.i("image", "" + image);
//                        }
//                        savedata("", image);
//                    }
//
//                    @Override
//                    public void onUploadMutliFail(Error error) {
//                    }
//                }, SPUtils.getInstance(context).getString("uptoken"));
//            }
//        } else {
//            savedata("", "");
//        }
//
//    }

    private void savedata() {

        Map<String, String> map = new HashMap<>();
        map.put("answer_id", "" + answer_id);
        map.put("paper_question_id", "" + paper_question_id);
        String answer = "";
        String answer_img = "";
        answer_img = mLists.get(i).answer_image;
        for (int i = 0; i < optionsList.size(); i++) {
            if (optionsList.get(i).isSelect == 1) {
                answer += optionsList.get(i).idx + ",";
            }
        }
        if (StringUtils.isNull(answer) && StringUtils.isNull(answer_img)) {
            hideLoadDialog();
            return;
        }
        if(answer.length()>1){
            answer = answer.substring(0,answer.length()-1);
        }
        map.put("answer", "" + answer+answer_img);
        map.put("answer_image", "" + answer_img);
        map.put("drawing_board_image", "");
        post("Task/saveAnswer", map, BaseBean.class, true);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                case PictureConfig.REQUEST_CAMERA:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = selectList.get(0);
                    String compressPath = localMedia.getCompressPath();

                    String qiniutoken = SPUtils.getInstance(App.getInstance()).getString("uptoken");
                    String key = System.currentTimeMillis() + "note.png";
                    QiniuUploadUtils.getInstance().uploadFile(compressPath, new QiniuUploadUtils.UploadListener() {
                        @Override
                        public void onUploadSuccess(String key) {
                            String yuming = SPUtils.getInstance(DoTheWorkActivity.this).getString("domain");
                            final String image = yuming + key;
                            ed_content.insertImage(image, "\" style=\"max-width:100%");
                            selectList.clear();
                        }

                        @Override
                        public void onUploadFail(Error error) {

                        }
                    }, qiniutoken);
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //包括裁剪和压缩后的缓存，要在上传成功后调用，注意：需要系统sd卡权限
//                    PictureFileUtils.deleteCacheDirFile(MainActivity.this);
                    // postMultiPhoto(selectList);
                    mLists.get(i).imglist = new ArrayList<LocalMedia>();
                    mLists.get(i).imglist.addAll(selectList);
                    //= selectList;
                    Log.i("imglist--->", "" + mLists.get(i).imglist);
//                    adapter.setList(selectList);
//                    adapter.notifyDataSetChanged();
                    break;
            }
        } else if (resultCode == 0) {
            if (data == null) {
                return;
            }
            if (!StringUtils.isNull(data.getStringExtra("filename"))) {
                QiniuUploadUtils.getInstance().uploadFile(data.getStringExtra("filename"), new QiniuUploadUtils.UploadListener() {
                    @Override
                    public void onUploadSuccess(String key) {
                        hideLoadDialog();
                        String yuming = SPUtils.getInstance(DoTheWorkActivity.this).getString("domain");
                        final String image = yuming + key;
                        ed_content.insertImage(image, "\" style=\"max-width:100%");
                    }

                    @Override
                    public void onUploadFail(Error error) {
                        hideLoadDialog();
                        Looper.prepare();
                        toast("插入图片失败");
                        Looper.loop();
                    }
                }, SPUtils.getInstance(DoTheWorkActivity.this).getString("uptoken"));
            } else {
                i = data.getIntExtra("order", 0);
                updateUi(i);
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        SPUtils.getInstance(App.getInstance()).put(answer_id + "worktime", tv_time.getText().toString());
        super.onDestroy();
    }

    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            // 进入相册 不需要的api可以不写
            PictureSelector.create(DoTheWorkActivity.this)
                    .openGallery(PictureMimeType.ofImage())
                    .theme(R.style.picture_default_style)
                    .maxSelectNum(maxSelectNum)
                    .minSelectNum(1)
                    .selectionMode(PictureConfig.MULTIPLE)
                    .previewImage(true)
                    .isCamera(true)
                    .enableCrop(false)
                    .compress(true)
                    .glideOverride(160, 160)
                    .previewEggs(true)
                    .withAspectRatio(1, 1)
                    .hideBottomControls(false)
                    .isGif(true)
                    .freeStyleCropEnabled(false)
                    .circleDimmedLayer(false)
                    .showCropFrame(false)
                    .showCropGrid(false)
                    .openClickSound(false)
                    .selectionMedia(selectList)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    };

    //    private void loadImageSimpleTarget(String str) {
//        Glide.with(context).asBitmap().load(str).into(new SimpleTarget<Bitmap>() {
//            @Override
//            public void onResourceReady(final Bitmap resource, Transition<? super Bitmap> transition) {
//                Drawable drawable = new BitmapDrawable(resource);
//                //Log.i("shouxieimg", i + "-----" + resource+"----"+paletteView);
//                //setBackgroundDrawable
//                //paletteView.setBackgroundDrawable(drawable);
//                //paletteView.setBackground(drawable);
//            }
//        });
//    }
    private void openPhoto() {
        PictureSelector.create(DoTheWorkActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(false)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void openCamera() {
        PictureSelector.create(DoTheWorkActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .selectionMedia(selectList)
                .forResult(PictureConfig.REQUEST_CAMERA);
    }
}
